// SiliconFlow API 配置
const API_URL = 'https://api.siliconflow.cn/v1/chat/completions';

// 处理来自 content script 的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === 'processText') {
    handleRequest(request, sender, sendResponse);
    return true; // 保持消息通道开启以支持异步响应
  }
});

// 从存储中获取API配置和提示语
async function getConfig() {
  return new Promise((resolve) => {
    chrome.storage.sync.get({
      apiKey: '',
      model: 'Qwen/Qwen2.5-7B-Instruct',
      prompts: {
        translate: '请将以下文本翻译成英文：\n',
        comment: '请对以下文本进行回复，要共情，要感同身受，要理解，要站在对方的角度思考问题，要更加口语化，不要太ai味儿，字数不超过50字：\n',
        summarize: '请总结以下文本的主要内容：\n'
      }
    }, resolve);
  });
}

async function handleRequest(request, sender, sendResponse) {
  try {
    const config = await getConfig();
    
    if (!config.apiKey) {
      chrome.runtime.openOptionsPage();
      throw new Error('请先在设置页面配置 API Key');
    }

    let prompt = '';
    switch (request.action) {
      case 'translate':
        prompt = config.prompts.translate + request.text;
        break;
      case 'comment':
        prompt = config.prompts.comment + request.text;
        break;
      case 'summarize':
        prompt = config.prompts.summarize + request.text;
        break;
      case 'custom':
        prompt = request.prompt + request.text;
        break;
    }

    const requestBody = {
      model: config.model,
      messages: [
        {
          role: 'system',
          content: '你是一个专业的文本分析助手。'
        },
        {
          role: 'user',
          content: prompt
        }
      ],
      temperature: 0.7,
      top_p: 0.7,
      max_tokens: 2000,
      stream: true // 启用流式响应
    };

    // 发送初始响应，表示开始处理
    sendResponse({
      success: true,
      streaming: true,
      result: '正在处理...'
    });

    const response = await fetch(API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${config.apiKey}`
      },
      body: JSON.stringify(requestBody)
    });

    if (!response.ok) {
      if (response.status === 401 || response.status === 403) {
        chrome.runtime.openOptionsPage();
        throw new Error('API Key 无效或已过期，请重新设置');
      }
      const errorData = await response.json();
      throw new Error(errorData.message || `请求失败: ${response.status}`);
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let fullText = '';
    let buffer = ''; // 添加缓冲区处理不完整的JSON

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      const chunk = decoder.decode(value);
      buffer += chunk;
      
      // 处理缓冲区中的完整行
      const lines = buffer.split('\n');
      buffer = lines.pop() || ''; // 保留最后一个不完整的行

      for (const line of lines) {
        if (line.trim() === '') continue; // 跳过空行
        if (line === 'data: [DONE]') continue; // 跳过结束标记

        if (line.startsWith('data: ')) {
          try {
            const data = JSON.parse(line.slice(6));
            if (data.choices && data.choices[0].delta?.content) {
              fullText += data.choices[0].delta.content;
              // 发送增量更新
              chrome.tabs.sendMessage(sender.tab.id, {
                type: 'streamUpdate',
                content: fullText
              });
            }
          } catch (e) {
            console.warn('解析流数据出错，跳过此行:', e);
            continue;
          }
        }
      }
    }

    // 处理缓冲区中剩余的数据
    if (buffer.trim() && buffer !== 'data: [DONE]') {
      try {
        const line = buffer.trim();
        if (line.startsWith('data: ')) {
          const data = JSON.parse(line.slice(6));
          if (data.choices && data.choices[0].delta?.content) {
            fullText += data.choices[0].delta.content;
          }
        }
      } catch (e) {
        console.warn('处理剩余数据出错:', e);
      }
    }

    // 发送最终结果
    chrome.tabs.sendMessage(sender.tab.id, {
      type: 'streamComplete',
      content: fullText
    });

  } catch (error) {
    console.error('API调用错误:', error);
    chrome.runtime.sendMessage({
      type: 'error',
      error: error.message
    });
  }
} 